<template>
  <div class="user-profile-container">
    <el-page-header title="返回" @back="$router.go(-2)" class="page-header">
      <template #content>
        <span class="header-title">校友信息详情</span>
      </template>
    </el-page-header>

    <el-card class="profile-card" v-loading="loading">
      <el-row :gutter="40" class="base-info">
        <el-col :span="6">
          <div class="avatar-wrapper">
            <el-image :src="userInfo.image" class="user-avatar">
              <template #error>
                <div class="avatar-error">
                  <i class="el-icon-user-solid"></i>
                </div>
              </template>
            </el-image>
            <div class="avatar-actions">
              <el-upload 
                :action="null" 
                :http-request="avatarUpdate"
                :show-file-list="false"
                class="avatar-upload"
              >
                <el-button type="primary" size="small" plain>更换头像</el-button>
              </el-upload>
              <div class="upload-tip" v-if="!userInfo.image">支持JPG/PNG格式</div>
            </div>
          </div>
        </el-col>


   

        <el-col :span="18">
          <el-form label-position="left" label-width="100px" class="info-form">
            <!-- 姓名和学号保持只读 -->
            <el-form-item label="姓名">
              <el-input v-model="userInfo.name" readonly />
            </el-form-item>

            <el-form-item label="学号">
              <el-input v-model="userInfo.studentId" readonly />
            </el-form-item>

            <!-- 用户名修改整合到表单项 -->
            <el-form-item label="用户名">
              <div class="flex-container">
                <el-input 
                  v-model="userInfo.username" 
                  placeholder="请输入新用户名"
                  class="username-input"
                />
                <el-popconfirm 
                  title="修改后将需要重新登录，确认修改？"
                  @confirm="usernameUpdate"
                >
                  <el-button 
                    slot="reference" 
                    type="primary" 
                    size="small"
                    :disabled="!userInfo.username"
                  >更新</el-button>
                </el-popconfirm>
              </div>
            </el-form-item>

            <el-form-item label="性别">
              <el-input :value="genderMap[userInfo.gender]" readonly />
            </el-form-item>
            <el-form-item label="密码">
              <el-button 
                type="primary" 
                size="small"
                @click="dialogVisible = true"
                icon="el-icon-lock"
              >修改密码</el-button>
            </el-form-item>
          </el-form>
          
        </el-col>
      </el-row>
      <el-tabs type="border-card" class="detail-tabs">
        <el-tab-pane label="学业信息">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="入学时间">
              {{ formatDate(userInfo.enrollmentDate) || '未填写' }}
            </el-descriptions-item>
            <el-descriptions-item label="毕业时间">
              {{ formatDate(userInfo.graduationDate) || '未填写' }}
            </el-descriptions-item>
            <el-descriptions-item label="所属院系">
              {{ userInfo.department || '未填写' }}
            </el-descriptions-item>
            <el-descriptions-item label="专业">
              {{ userInfo.major || '未填写' }}
            </el-descriptions-item>
            <el-descriptions-item label="籍贯">
              {{ userInfo.nativePlace || '未填写' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="联系方式">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="联系电话">
              {{ userInfo.phoneNumber || '未填写' }}
            </el-descriptions-item>
            <el-descriptions-item label="电子邮箱">
              {{ userInfo.email || '未填写' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>

      <!-- 密码修改对话框 -->
      <el-dialog title="修改密码" :visible.sync="dialogVisible" width="30%" @closed="handleDialogClose">
        <el-form :model="passwordForm" label-width="100px" ref="passwordForm">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="passwordForm.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';


export default {
  data() {
    return {
      loading: false,
      userInfo: {},
      genderMap: {
        0: '未知',
        1: '男',
        2: '女'
      },
      dialogVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
    }
  },
  mounted() {
    this.loadUserData();
  },
  methods: {
    async loadUserData() {
      try {
        this.loading = true
        const username = this.$route.params.username
        const res = await axios.get(`http://localhost:8080/AlumniInfo/${username}`)

        if (res.data?.code === 1) { // 使用可选链避免undefined
          this.userInfo = {
            ...res.data.data,
            phone: res.data.data.phone || '',
            email: res.data.data.email || ''
          }
          console.log(res.data.data.id)
        }
      } catch (error) {
        this.$message.error('数据加载失败')
      } finally {
        this.loading = false

      }
    },
    async avatarUpdate(file) {

      try {
        const username = this.$route.params.username
        const formData = new FormData();
        formData.append('image', file.file);
        const res = await axios.post(`http://localhost:8080/AvatarUpdate/${username}`, formData);
        this.userInfo.image = res.data.url;
        this.loadUserData();
      } catch (error) {
        this.$message.error('上传失败');
      }
    },
    async usernameUpdate() {
      try {
        if (!this.userInfo.username) {
          this.$message.warning('用户名不能为空');
          return;
        }

        const idAndUsername = {
          id: this.userInfo.id,
          username: this.userInfo.username
        }

        const res = await axios.post("http://localhost:8080/updateUsername", idAndUsername);

        if (res.data.code === 1) {
          this.$message.success("用户名修改成功，请重新登录");
          // 清除用户状态
          localStorage.removeItem('token');
          this.$router.push('/login');
        }
      } catch (error) {
        console.error('修改失败:', error);
        this.$message.error(error.response?.data?.message || '修改失败');
      }
    },
    handlePasswordSubmit() {
      // 前端验证
      if (!this.passwordForm.oldPassword) {
        this.$message.warning('请输入原密码')
        return
      }
      if (this.passwordForm.oldPassword !== this.userInfo.password) {
        this.$message.warning('原密码错误')
        return
      }
      if (!this.passwordForm.newPassword) {
        this.$message.warning('请输入新密码')
        return
      }
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword ) {
        this.$message.warning('两次输入的新密码不一致')
        return
      }
      
      // 通过验证后调用原修改方法
      this.passwordUpdate()
    },

    // 修改后的密码更新方法
    async passwordUpdate() {
      try {
        const params = {
          id: this.userInfo.id,
          password: this.passwordForm.newPassword
        }
        
        const res = await axios.post("http://localhost:8080/updatePassword", params)
        
        if (res.data.code === 1) {
          this.$message.success("密码修改成功，请重新登录")
          this.dialogVisible = false
          // 清除用户状态
          this.$router.push('/login')
        }
      } catch (error) {
        console.error('修改失败:', error)
        this.$message.error(error.response?.data?.message || '修改失败')
      }
    },

    // 关闭对话框时重置表单
    handleDialogClose() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    },
    formatDate(time) {
      return time ? new Date(time).toLocaleString() : '未知时间'
    },

  }
}
</script>

<style lang="scss" scoped>
.user-profile-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;

  .page-header {
    margin-bottom: 30px;

    .header-title {
      font-size: 24px;
      color: #303133;
    }
  }

  .profile-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    .base-info {
      margin-bottom: 30px;

      .avatar-wrapper {
        position: relative;

        .user-avatar {
          width: 100%;
          height: 200px;
          border-radius: 4px;
          background: #f5f7fa;

          :deep(.el-image__inner) {
            transition: all 0.3s;

            &:hover {
              transform: scale(1.05);
            }
          }
        }

        .avatar-error {
          @extend .user-avatar;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 40px;
          color: #909399;
        }

        .upload-tip {
          text-align: center;
          color: #909399;
          margin-top: 10px;
        }
      }

      .info-form {
        :deep(.el-input__inner) {
          background-color: #f5f7fa;
          border-color: #e4e7ed;
          color: #606266;
        }
      }
    }

    .detail-tabs {
      margin-top: 20px;

      .bio-content {
        line-height: 1.6;
        white-space: pre-wrap;
      }
    }
  }
}
</style>